﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using BEGDC.PreContract.BLL;
using BEGDC.Utility.Castle;

namespace PreContractWeb.Administration
{
    public partial class DatabaseSnapshot : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SetLabelSnapshotCreationTime();
                this.btnCreateDatabaseSnapshot.Attributes.Add("onclick", "return confirm_create_snapshot();");
            }
        }

        protected string SnapshotName
        {
            get
            {
                if (Session["SnapshotName"] == null)
                {
                    Session["SnapshotName"] = ConfigurationManager.AppSettings["DbSnapshotName"];
                }
                return (string)Session["SnapshotName"];
            }
        }

        private void SetLabelSnapshotCreationTime()
        {
            ISnapshotOperation snapshotOperation = (ISnapshotOperation)AppContainer.Instance[Services.CONST_SnapshotOperation_Service];
            DateTime snapshotCreationTime = snapshotOperation.GetSnapshotCreationTime(SnapshotName);
            if (snapshotCreationTime != DateTime.MinValue)
            {
                this.lblLastDatabaseSnapshotTime.Text = snapshotCreationTime.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                this.lblLastDatabaseSnapshotTime.Text = "No snapshot existing!";
            }
        }

        protected void btnCreateDatabaseSnapshot_OnClick(object sender, EventArgs e)
        {
            ISnapshotOperation snapshotOperation = (ISnapshotOperation)AppContainer.Instance[Services.CONST_SnapshotOperation_Service];
            string logicalFileName = snapshotOperation.GetLogicalFileName();
            string fileName = DateTime.UtcNow.Date.ToShortDateString();
            fileName = fileName.Replace("/", "");
            string fileStreamPath = Path.Combine(snapshotOperation.GetSqlServerDefaultDataFilePath(), fileName);
            
            snapshotOperation.CreateSnapshot(SnapshotName, logicalFileName, fileStreamPath);
            SetLabelSnapshotCreationTime();
        }
    }
}